
package com.android.image;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.widget.ImageView;

import com.android.image.ImageIOThread.CacheImage;

public class CacheTask implements Runnable, VGongyiSetting {

    private String mUrl;
    private Handler mHandler;
    private ImageView mImageView;
    private ImageIOThread mIoThread;

    public CacheTask(String url, ImageView imageView) {
        mUrl = url;
        mImageView = imageView;
    }
    
    protected CacheTask(String url,Handler handler, ImageView imageView,Bitmap bitmap) {
        mUrl = url;
        mHandler = handler;
        mImageView = imageView;
    }

    public String getUrl() {
        return mUrl;
    }

    public void setUrl(String mUrl) {
        this.mUrl = mUrl;
    }

    public Handler getHandler() {
        return mHandler;
    }

    public void setHandler(Handler mHandler) {
        this.mHandler = mHandler;
    }

    public ImageView getImageView() {
        return mImageView;
    }

    public void setImageView(ImageView mImageView) {
        this.mImageView = mImageView;
    }


    @Override
    public void run() {
    	
    	Bitmap bitmap = getFromServer();
	    
    	if (bitmap != null) {
    		showBitmap(bitmap);
    	}
    	bitmap = null;
    }

    public void setIOThread(ImageIOThread ioThread) {
        mIoThread = ioThread;
    }
    
    /**
     * @param bitmap
     */
    protected void showBitmap(final Bitmap bitmap) {
        mHandler.post(new Runnable() {
            public void run() {
                
            	if(mImageView!=null&&!TextUtils.isEmpty(mImageView.getTag().toString())&&mImageView.getTag().equals(mUrl))
            	mImageView.setBackgroundDrawable(new BitmapDrawable(bitmap));
                
            }
        });
    }
    
    private Bitmap getFromServer() {
        Bitmap bm = null;
        try {
            HttpGet httpRequest = new HttpGet(new URL(mUrl).toURI());
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
            HttpEntity entity = response.getEntity();
            BufferedHttpEntity bufHttpEntity = null;
            bufHttpEntity = new BufferedHttpEntity(entity);
            InputStream in = bufHttpEntity.getContent();
            bm = cacheBitmap(mUrl, in);
            
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bm;
    }
    /**
     * @param bitmap
     * @param url 
     */
    protected Bitmap cacheBitmap(String url, InputStream in) {

    	String encodeUlr = URLEncoder.encode(url);
  
        if (in == null) {
            return null;
        }
        Bitmap bitmap = null;
        if (mIoThread != null && VGongyiApp.DEFAULT_SDCARD_PATH != null) {
            try {
            	CacheImage cacheimg = new CacheImage(in, encodeUlr);
				mIoThread.saveBitmap(cacheimg);
				
				File file = new File(VGongyiApp.DEFAULT_SDCARD_PATH,encodeUlr);
				bitmap = BitmapFactory.decodeStream(new FileInputStream(file));
				TPManager.mImageCache.put(encodeUlr, new SoftReference<Bitmap>(bitmap));
				return bitmap;
			} catch (Exception e) {
				bitmap = null;
			}
        }else{
          bitmap = BitmapFactory.decodeStream(in);
          TPManager.mImageCache.put(encodeUlr, new SoftReference<Bitmap>(bitmap));
          return bitmap;
        }
        return null;
    }
    
    /**
     * @param url 
     * @return
     */
    public String getImageName(String url) {
        return Uri.encode(url);
    }
}